package com.jy.rhin.domain.document.filter;

import com.jy.rhin.sdk.dto.document.DocumentContentDto;
import com.jy.rhin.sdk.dto.document.DocumentProvideAndRegisterDto;
import com.jy.rhin.sdk.dto.document.DocumentSubmissionSetDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @author dhl
 * @date 2022/6/2
 * @Description
 */
@Slf4j
@Service
public class DocumentFilterChain {

    @Resource
    private DocumentFilterFactory documentFilterFactory;

    /**
     * 文档提交过滤器校验
     *
     * @param dto
     */
    public void provide(DocumentProvideAndRegisterDto dto) {
        doFilter(DocumentFilterDescEnum.FilterType.PROVIDE, dto.getSubmissionSet(), dto.getDocuments());
    }

    /**
     * 文档注册过滤器校验
     *
     * @param submissionSet
     */
    public void register(DocumentSubmissionSetDto submissionSet) {
        doFilter(DocumentFilterDescEnum.FilterType.REGISTER, submissionSet, Collections.emptyList());
    }

    /**
     * 文档元数据更新过滤器校验
     *
     * @param submissionSet
     */
    public void update(DocumentSubmissionSetDto submissionSet) {
        doFilter(DocumentFilterDescEnum.FilterType.UPDATE, submissionSet, Collections.emptyList());
    }

    private void doFilter(DocumentFilterDescEnum.FilterType filterType, DocumentSubmissionSetDto submissionSet, List<DocumentContentDto> documents) {
        List<DocumentFilter> filterList = documentFilterFactory.getFilterList(filterType);
        String typeName = filterType.getTypeName();
        if (CollectionUtils.isEmpty(filterList)) {
            log.warn("==> 未找到{}过滤器，请检查过滤器配置", typeName);
            return;
        }
        int size = filterList.size();
        log.debug("==> 发现{}个{}过滤器, 校验开始", size, typeName);
        for (int i = 0; i < size; i++) {
            DocumentFilter filter = filterList.get(i);
            if (filter.shouldFilter(submissionSet, documents)) {
                filter.doFilter(submissionSet, documents);
                log.debug("=== 第 {} 个{}过滤器: {} [校验完成]", i, typeName, filter.filterDesc().getFilterName());
            } else {
                log.debug("=== 第 {} 个{}过滤器: {} [跳过]", i, typeName, filter.filterDesc().getFilterName());
            }
        }
        log.debug(" <== {}过滤器校验结束", typeName);
    }
}
